package com.tricycle.scada.mqtt.realtime;

import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Log4j2
@Component
public class RealtimeRedisCleanHandler {

    private Long expiredTime = 3600 * 1000L;
    private final RedisTemplate<String, String> redisTemplate;

    public RealtimeRedisCleanHandler(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Scheduled(cron = "0 */5 * * * *")
    public void handle() {
        long currentTime = System.currentTimeMillis();
        long beforeTimestamp = (currentTime - expiredTime) / 1000;
        logger.info("Expired check start...");
        Set<String> tags = redisTemplate.opsForSet().members("tags");
        if (tags != null) {
            for (String tag : tags) {
                logger.debug("Delete expired tag value, {} timestamp before {}.", tag, beforeTimestamp);
                redisTemplate.opsForZSet().removeRangeByScore(tag, Double.NEGATIVE_INFINITY, beforeTimestamp);
            }
        }
        logger.info("Expired value check end cost {} ms.", System.currentTimeMillis() - currentTime);
    }
}
